package com.example.demo;

import com.example.demo.annatationtest.sub.UserService;
import com.example.demo.config.AppConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("test")
@EnableConfigurationProperties(AppConfig.class)
@Slf4j
public class TestController {

    @Autowired
    private UserService userService;

    @Autowired
    private AppConfig appConfig;

    @RequestMapping("get")
    public String get() {
        return "test";
    }

    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @RequestMapping("get2")
    public void get2() throws InterruptedException {
        // 创建计数器，用于等待所有任务完成
        int taskCount = 100000000;
        CountDownLatch latch = new CountDownLatch(taskCount);

        // 启动监控线程
        startMonitorThread(threadPoolTaskExecutor);

        // 提交任务
        for (int i = 0; i < taskCount; i++) {
            final int taskNum = i;
            threadPoolTaskExecutor.execute(() -> {
                try {
                    // 模拟任务处理
                    TimeUnit.MILLISECONDS.sleep(1);
                    System.err.println("Task " + taskNum + " completed by " + Thread.currentThread().getName());
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                } finally {
                    latch.countDown();
                }
            });
        }

        // 等待所有任务完成
        latch.await();
        System.out.println("All tasks completed!");
    }


    private static void startMonitorThread(ThreadPoolTaskExecutor executor) {
        Thread monitorThread = new Thread(() -> {
            while (!executor.getThreadPoolExecutor().isTerminated()) {
                try {
                    // 每隔1秒打印一次线程池状态
                    TimeUnit.SECONDS.sleep(1);

                    log.info(
                            "ThreadPool Stats: " +
                                    "core={}, active={}, current={}, max={}, queue={}, completed={}",
                            executor.getCorePoolSize(),
                            executor.getActiveCount(),
                            executor.getPoolSize(),
                            executor.getMaxPoolSize(),
                            executor.getThreadPoolExecutor().getQueue().size(),
                            executor.getThreadPoolExecutor().getCompletedTaskCount() );
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        });

        monitorThread.setDaemon(true);
        monitorThread.setName("thread-pool-monitor");
        monitorThread.start();
    }
}
